/*
 * @Author: Marte
 * @Date:   2016-10-28 10:07:12
 * @Last Modified by:   Marte
 * @Last Modified time: 2016-11-04 17:05:24
 */

'use strict';

var sequelizeService = require('../utils/sequelizeService');

var Pic = sequelizeService.models.Pic;
var fs = require('fs');
var path = require('path');
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
var moment = require('moment')

var _ = require('underscore');
var Promise = require('bluebird');

var controller = {

};

var resourcePath;

if (process.env.NODE_ENV === 'development') {
    resourcePath = '/resource_dev';
} else {
    resourcePath = '/resource';
}


var range = function(start, end) {
    var array = [];
    for (var i = start; i < end; ++i) {
        array.push(i);
    }
    return array;
};

/**
 * [getAllJson 获取相片]
 * @param  {[type]}   req  [
 * start:记录开始位置,
 * size:查找记录数,
 * countall:是否要计算总记录数
 * ]
 * @param  {[type]}   res  [json]
 * @param  {Function} next [description]
 * @return {[type]}        [{count:Number,rows:Array}]
 */
controller.getAllJson = function(req, res, next) {
    var offset = null;
    if (req.query.start) {
        offset = parseInt(req.query.start);
    }
    var size = null;
    if (req.query.size) {
        size = parseInt(req.query.size);
    }
    var s = req.query.search;

    var countall = 0;
    if (req.query.countall) {
        countall = parseInt(req.query.countall);
    }

    var getPic;
    if (countall) {
        getPic = Pic.fetchPageJsonAndCountAll(offset,
            size, s);
    } else {
        getPic = Pic.fetchPageJson(offset, size, s);
    }
    getPic
        .then(function(_result) {
            if (countall) {
                return res.json(_result);
            } else {
                return res.json({
                    rows: _result
                });
            }
        })
        .catch(function(err) {
            return res.status(500).json({
                error: '无法读取数据',
                syserror: err.message
            });
        })
        .error(function(err) {
            return res.status(400).json({
                error: '无法读取数据',
                syserror: err.message
            });
        });
};

/**
 * [postUploadfileToJson 上传图片到服务器]
 * @param  {[type]}   req  [description]
 * @param  {[type]}   res  [description]
 * @param  {Function} next [description]
 * @return {[type]}        [description]
 */
controller.postUploadfileToJson = function(req, res, next) {
    //存放的目录对应为 /resource
    //console.log(req);
    var fileData = req.files.file;
    var filePath = fileData.path;
    var fileSize = fileData.size;
    var originalFilename = fileData.originalFilename;

    if (originalFilename) {

        var filetype = fileData.type.split('/')[0];
        var imagetype = fileData.type.split('/')[1];

        fs.readFile(filePath, function(err, data) {
            if (err) {
                return next(err);
            }
            //重命名为年月日时间（精确到1毫秒）
            var randomstr = range(0, 3).map(function(x) {
                return Math.floor(Math.random() * 10);
            }).join('');
            var fileName = (originalFilename.lastIndexOf('.') > 0) ? originalFilename.substring(0, originalFilename.lastIndexOf('.')) : originalFilename;
            var fileFullName = moment().format('YYMMDDHHmmssSSS') + randomstr + '.' + imagetype;
            var newPath = path.join(process.cwd(), resourcePath, fileFullName);

            fs.writeFile(newPath, data, function(err) {
                if (err) {
                    return res.status(400).json({
                        error: '文件保存失败.',
                        syserror: err
                    });
                }

                //保存到数据库
                Pic.create({
                        fileName: fileName,
                        fileFullName: fileFullName,
                        origName: originalFilename
                    })
                    .then(function(_resource) {
                        return res.status(200).json(_resource.get({ plain: true }));
                    })
                    .catch(function(err) {
                        return res.status(500).json({
                            error: '保存到数据库失败.',
                            syserror: err
                        });
                    })
                    .error(function(err) {
                        return res.status(400).json({
                            error: '保存到数据库失败.',
                            syserror: err.message
                        });
                    });
            });
        });

    } else {
        res.status(400).json({
            error: '无效的文件'
        });
    }

};

controller.deletePic = function(req, res, next) {
    var picId = req.params.id;
    var fileFullName = null;
    if (picId) {
        Pic.findById(picId)
            .then(function(pic) {
                if (pic) {
                    fileFullName = pic.fileFullName;
                    return pic.destroy();
                } else {
                    return Promise.reject(new Error('资源已被移除'));
                }

            })
            .then(function() {
                if (fileFullName) {
                    var filePath = path.join(process.cwd(), resourcePath, fileFullName);
                    fs.unlink(filePath, function(err) {
                        if (err) {
                            return Promise.reject(err);
                        } else {
                            return Promise.resolve(true);
                        }
                    });
                } else {
                    return Promise.reject(new Error('资源已从磁盘删除'));
                }
            })
            .then(function() {
                return res.status(200).json({ success: 'OK' });
            })
            .error(function(err) {
                return res.status(400).json({
                    error: '删除失败.',
                    syserror: err.message
                });
            })
            .catch(function(err) {
                return res.status(500).json({
                    error: '删除失败.',
                    syserror: err.message
                });
            });
    } else {
        res.status(400).json({
            error: '错误的参数'
        });
    }
};

controller.registerPath = function(router) {

    //获取相片资源
    router.addPathGetHanlder('/api/pics', controller.getAllJson);

    /*上传文件并保存到数据库*/
    router.addPathPostHanlder('/pics/uploadFiles', multipartMiddleware, controller.postUploadfileToJson);

    /*删除文件及数据库记录*/
    router.addPathDeleteHanlder('/pics/:id', controller.deletePic);
};

module.exports = controller;
